from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View
from django.http import HttpResponseForbidden
from login.models import User
from corp.models import TourBooking, Trip


# Create your views here.


class IndexView(View):
    """
        首页视图
    """

    def get(self, request):
        # 判断是否登录
        username = request.COOKIES.get('username')
        if username:
            # 获取用户昵称
            nickname = request.session.get('nickname')
            identity = request.session.get('identity')
            if nickname:
                # 获取对应用户
                user = User.objects.get(username=username)
                # 查询对应订单
                tour_bookings = TourBooking.objects.filter(guests=user)
                # 对应行程
                trips = []
                booking_list = []
                for tour_booking in tour_bookings:
                    booking_item = {
                        'id': tour_booking.id,
                        'corp': tour_booking.corp.name,
                        'price': tour_booking.price,
                    }
                    booking_list.append(booking_item)
                    tour_trips = Trip.objects.filter(booking=tour_booking)
                    for tour_trip in tour_trips:
                        trips.append(tour_trip)

                # print('tour_bookings: ', tour_bookings)
                # print('trips: ', trips)

                # 封装数据
                trip_list = []
                fmt = '%Y-%m-%d'
                for trip in trips:
                    trip_item = {
                        'date_start': trip.date_start.strftime(fmt),
                        'date_end': trip.date_end.strftime(fmt),
                        'attraction': trip.attraction,
                    }
                    trip_list.append(trip_item)

                context = {
                    'nickname': nickname,
                    # 'identity': identity,
                    'trip_list': trip_list,
                    'booking_list': booking_list,
                }
                if identity == User.UNSURE:
                    context['other_info'] = '待审核'
            else:
                return HttpResponseForbidden('登录状态有误')
        else:
            # 未登录
            context = {
                'status': 'OK',
            }

        return render(request, 'contents/index.html', context)
